package com.woniu.houtai.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.houtai.config.Converter;
import com.woniu.houtai.entity.Business;
import com.woniu.houtai.entity.Product;
import com.woniu.houtai.entity.Shop;
import com.woniu.houtai.entity.Type;
import com.woniu.houtai.service.BusinessService;
import com.woniu.houtai.service.ShopService;
import com.woniu.houtai.service.TypeService;
import com.woniu.houtai.utils.CookieUtils;
import com.woniu.houtai.utils.FileUtils;
import com.woniu.houtai.utils.JwtUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.Multipart;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author firstGroup
 * @since 2023-02-22 09:45:58
 */
@Controller
@RequestMapping("/shop")
public class ShopController {
    private static final String pathName = "http://192.168.201.161:10002/imgs/";

    @Autowired
    ShopService shopService;

    @Autowired
    BusinessService businessService;

    @Autowired
    TypeService typeService;

    @RequestMapping("/selectByBusinessId")
    @ResponseBody
    public Page<Shop> selectByBusinessId(Integer currentPage, Integer pageSize, HttpServletRequest request) {
        Page<Product> productPage = new Page<>(currentPage, pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        Business business = getCurrentBusiness(request);
        Integer businessId = business.getId();
        queryWrapper.eq("business_id", businessId);
        return shopService.selectByBusinessId(currentPage, pageSize, businessId);
    }


    @RequestMapping("/insert")
    @ResponseBody
    public String insert(String name, String detail, MultipartFile imageUrl, @RequestParam List<String> typeList, HttpServletRequest request) throws IOException {

        Business business = getCurrentBusiness(request);
        Integer businessId = business.getId();
        Shop shop = shopService.selectByBusinessIdAndName(businessId, name);
        String ip = "192.168.201.161"; //目标ip
        String filePath = "//"+ip+"/imgs/";
        String sqlFileName = null;


        if (shop == null) {

            // 图片保存
            if (imageUrl.isEmpty()) {
                return "fail";
            } else {
                String newFilename = FileUtils.copy(imageUrl, filePath);

                //写入数据库
                //创建数据库中的图片地址
                sqlFileName = pathName + newFilename;
                Integer result = shopService.insert(name, detail, sqlFileName, businessId);
                System.out.println("result: " + result);
                Shop newShop = shopService.selectByBusinessIdAndName(businessId, name);
                Integer shopId = newShop.getId();
                for (String s : typeList) {
                    Type type = new Type();
                    type.setTypeName(s);
                    type.setShopId(shopId);
                    typeService.insert(type);
                }
                return "ok";
            }
        } else {
            return "您已有此名称的店铺";
        }
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Integer id,String name, String detail, MultipartFile imageUrl, Integer businessId, @RequestParam List<String> typeList) throws IOException {
        Shop shop =shopService.selectById(id);
        if (imageUrl!=null){
            System.out.println("image"+imageUrl.getSize());
            String ip = "192.168.201.161"; //目标ip
            String filePath = "//"+ip+"/imgs/";
            String sqlFileName = null;
            String newFilename = FileUtils.copy(imageUrl, filePath);

            //写入数据库
            //创建数据库中的图片地址
            sqlFileName = pathName + newFilename;
            Integer result=shopService.update(id,name,detail,sqlFileName,businessId);
        }else {
            Integer result=shopService.update(id,name,detail,shop.getImgSrc(),businessId);
        }
        if(typeService.deleteByShopId(id)!=null){
            for (String s : typeList) {
                Type type = new Type();
                type.setTypeName(s);
                type.setShopId(id);
                typeService.insert(type);
            }
        }
        return "ok";
    }

    @RequestMapping("/selectShopByBusinessId")
    @ResponseBody
    Page<Shop> selectShopByBusinessId(Integer currentPage,Integer pageSize,HttpServletRequest request){
        if(currentPage==null||pageSize==null){
            currentPage=1;
            pageSize=3;
        }
        Business business = getCurrentBusiness(request);
        Integer businessId = business.getId();
        return shopService.selectByBusinessId(currentPage,pageSize,businessId);
    }

    @RequestMapping("selectShopByShopId")
    public String selectShopByShopId(Integer shopId, Model model){
        System.out.println("shopId"+shopId);
        Shop shop = shopService.selectById(shopId);
        List<String> typeList = typeService.selectTypeNameByShopId(shopId);
        model.addAttribute("shop",shop);
        model.addAttribute("typeList",typeList);
        System.out.println(shop.getName());

        return "shopDetail";
    }


    private Business getCurrentBusiness(HttpServletRequest request) {
        //获取已登录商家信息
        // 1.先从request中拿到token
        // 2.从token中获取用户名
        // 3.根据用户名查询到用户信息
        String userTokenFromCookie = CookieUtils.getUserTokenFromCookie(request);
        String account = JwtUtils.getAccountWithoutException(userTokenFromCookie);
        return businessService.getBusinessByName(account);
    }
    @RequestMapping("shopList")
    @ResponseBody
    public List<Shop> getMyShop(HttpServletRequest request){
        Business business = getCurrentBusiness(request);
        List<Shop> shopList = shopService.selectByOnlyBusinessId(business.getId());
        return shopList;
    }
}

